package regex;

import java.util.regex.Pattern;
import utils.Log;
import utils.StringUtils;

public class PhoneNumberPattern {

  private static final Pattern PHONE_NUMBER_PATTERN =
      Pattern.compile("[\\+]?[0-9]{0,4}[-]?[((\\s)|(0-9))]{3,11}");

  // 验证带区号的
  private static final Pattern TELE_PHONE_PATTERN1=
      Pattern.compile("^[0][1-9]{2,3}-[0-9]{5,10}$");

  // 验证没有区号的
  private static final Pattern TELE_PHONE_PATTERN2=
      Pattern.compile("^[1-9]{1}[0-9]{5,8}$");

  // 匹配所有号码（手机卡 + 数据卡 + 上网卡）
  private static final Pattern CHINA_MOBILE_PATTERN =
      Pattern.compile("^(?:\\+?86)?1(?:3\\d{3}|5[^4\\D]\\d{2}|8\\d{3}|7(?:[35678]\\d{2}|4(?:0\\d|1[0-2]|9\\d))|9[01356789]\\d{2}|66\\d{2})\\d{6}$");

  // 344, 434, 443组合模式
  private static final Pattern MOBILE_PATTERN =
      Pattern.compile("^(\\+?86)?([0-9]{3}(\\s)?[0-9]{4}(\\s)?[0-9]{4})|([0-9]{4}(\\s)?[0-9]{3}(\\s)?[0-9]{4})|([0-9]{4}(\\s)?[0-9]{4}(\\s)?[0-9]{3})");

  public static void main(String[] args) {
    testCase();
  }


  static void testCase() {
    String p1 = "188 1038 7954";
    String p2 = "18810387954";
    String p3 = "188 10387954";
    String p4 = "+8618810387954";
    String p5 = "021-12345";
    String p6 = "021-61266126";
    String p7 = "2019-11";
    String p8 = "52";
    String p9 = "2019";
    String p10 = "1881 038 7954";
    String p11 = "1881 0387 954";
    String p12 = "1881038 7954";

    Log.vn("p1:" + matches(p1));
    Log.vn("p2:" + matches(p2));
    Log.vn("p3:" + matches(p3));
    Log.vn("p4:" + matches(p4));
    Log.vn("p5:" + matches(p5));
    Log.vn("p6:" + matches(p6));
    Log.vn("p7:" + matches(p7));
    Log.vn("p8:" + matches(p8));
    Log.vn("p9:" + matches(p9));
    Log.vn("p10:" + matches(p10));
    Log.vn("p11:" + matches(p11));
    Log.vn("p12:" + matches(p12));
  }


  public static boolean matches(String text) {
    if (StringUtils.isEmpty(text)) {
      return false;
    }

    // text = trimAll(text);
    boolean  tel1 = TELE_PHONE_PATTERN1.matcher(text).matches();
    boolean  tel2 = TELE_PHONE_PATTERN2.matcher(text).matches();
    boolean  mob1 = CHINA_MOBILE_PATTERN.matcher(text).matches();
    boolean  mob2 = MOBILE_PATTERN.matcher(text).matches();

    return tel1 || tel2 || mob1 || mob2;
  }

  public static String trimAll(String text) {
    if (StringUtils.isEmpty(text)) {
      return "";
    }
    StringBuilder sb = new StringBuilder();
    for (int i = 0; i < text.length(); i++) {
      if (text.charAt(i) == ' ') {
        continue;
      }
      sb.append(text.charAt(i));
    }

    return sb.toString();
  }

}
